<?php
namespace app\bsadmin\controller;
use think\facade\Cache;
use think\facade\View;
use think\facade\Validate;
use app\common\model\Area as AreaModel;
use helper\PinYin;
class Area extends Base
{
    public function index()
    {
        if (request()->isAjax()) {
            $G=request()->get();
            if (empty($G['id'])) {
                return $this->ajaxReturn('',0,AreaModel::getSelect(['pid'=>0]));
            }else{
                return $this->ajaxReturn('',0,AreaModel::getSelect(['pid'=>$G['id']]));
            }
        }else{
            return View::fetch();
        }
    }
    /**
     * 编辑地区
     */
    public function edit($id)
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'title'     => 'require|max:50',
	            'alias'  	=> 'unique:area',
            ];
            $msg  =   [
                'title.require' => 'Title 不能为空', 
                'title.max'     => 'Title 不能超过50个字符',
	            'alias.unique' 	=> '别名已存在',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $AreaModel=AreaModel::find($id);
            $AreaModel->title    = $D['title'];
            $AreaModel->alias    = $D['alias'];
            $AreaModel->level    = $D['level'];
            $AreaModel->status   = $D['status'];
            if (isset($D['sort'])&&intval($D['sort']))
                $AreaModel->sort    = intval($D['sort']);
            if (!empty($D['pid'])) 
	            $AreaModel->pid   	= $D['pid'];
            $PinYin=new PinYin;
            $p=$PinYin->get_all_py($D['title']);
            $AreaModel->letter    = $PinYin->get_first_letter($p);
            if($AreaModel->save()){
                return $this->ajaxReturn('保存成功');
            }else{
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            $area=AreaModel::getCate()->toArray();
            View::assign('area',$area);
            $Find=AreaModel::where(['id'=>$id])->find();
            View::assign('Find',$Find);
            return View::fetch('add');
        }
    }
    /**
     * 添加地区
     */
    public function add()
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'title'     => 'require|max:50',
	            'alias'  	=> 'unique:area',
            ];
            $msg  =   [
                'title.require' => 'Title 不能为空', 
                'title.max'     => 'Title 不能超过50个字符',
	            'alias.unique' 	=> '别名已存在',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $AreaModel=new AreaModel;
            $AreaModel->title    = $D['title'];
            $AreaModel->alias    = $D['alias'];
            $AreaModel->level    = $D['level'];
            $AreaModel->status   = $D['status'];
            if (isset($D['sort'])&&intval($D['sort']))
                $AreaModel->sort    = intval($D['sort']);
            if (!empty($D['pid'])){
	            $AreaModel->pid   	= $D['pid'];
            }else{
                $AreaModel->pid     = 0;
            }
            $PinYin=new PinYin;
            $p=$PinYin->get_all_py($D['title']);
            $AreaModel->letter    = $PinYin->get_first_letter($p);
            if($AreaModel->save()){
                return $this->ajaxReturn('保存成功');
            }else{
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            $area=AreaModel::getCate()->toArray();
            View::assign('area',$area);
            return View::fetch();
        }
    }
    public function setAreaStatus($id,$status)
    {
        $AreaModel=AreaModel::where(['id'=>$id])->find();
        $AreaModel->status=$status;
        if ($AreaModel->save()) {
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-200);
        }
    }
    public function setAreaHot($id,$status)
    {
        $AreaModel=AreaModel::where(['id'=>$id])->find();
        $AreaModel->hot=$status;
        if ($AreaModel->save()) {
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-200);
        }
    }
    public function delete($id)
    {
        $AreaModel=AreaModel::where(['id'=>$id])->find();
        if ($AreaModel->delete()) {
            $this->updateFileCache();
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-200);
        }
    }
    public function updateFileAjax()
    {
        $this->updateFileCache();
        return $this->ajaxReturn('更新成功');
    }
    public function updateFileCache()
    {
        $Arealist=AreaModel::getCache()->toArray();
        Cache::set('arealist',$Arealist);
        $Data=AreaModel::alias('city')->where(['city.level'=>2])
        ->join('area p','p.id=city.pid')
        ->field('city.id,city.status,p.status as pstatus,city.title,city.letter,city.hot,city.level')->order('city.sort asc,city.id asc')->select()->toArray();
        $Citylist=[];
        $CitylistAll=[];
        foreach ($Data as $k => $v) {
            if ($v['status']&&$v['pstatus']) {
                if ($v['hot']) {
                    if (empty($Citylist['A0']['title']))
                        $Citylist['A0']['title']='热门城市';
                    $Citylist['A0']['data'][]=['id'=>$v['id'],'level'=>$v['level'],'title'=>$v['title']];
                }
                if (empty($Citylist[strtoupper($v['letter']).'1']['title']))
                    $Citylist[strtoupper($v['letter']).'1']['title']=strtoupper($v['letter']);
                $Citylist[strtoupper($v['letter']).'1']['data'][]=['id'=>$v['id'],'level'=>$v['level'],'title'=>$v['title']];
            }
            if ($v['hot']) {
                if (empty($CitylistAll['A0']['title']))
                    $CitylistAll['A0']['title']='热门城市';
                $CitylistAll['A0']['data'][]=['id'=>$v['id'],'level'=>$v['level'],'title'=>$v['title']];
            }
            if (empty($CitylistAll[strtoupper($v['letter']).'1']['title']))
                $CitylistAll[strtoupper($v['letter']).'1']['title']=strtoupper($v['letter']);
            $CitylistAll[strtoupper($v['letter']).'1']['data'][]=['id'=>$v['id'],'level'=>$v['level'],'title'=>$v['title']];
        }
        ksort($Citylist);
        ksort($CitylistAll);
        $CacheCity=[];
        $CacheCityAll=[];
        foreach ($Citylist as $k => $v) $CacheCity[]=$v;
        foreach ($CitylistAll as $k => $v) $CacheCityAll[]=$v;
        Cache::set('citylist',$CacheCity);
        Cache::set('citylistall',$CacheCityAll);
    }
}
